package com.zhkj.txg.module.home.ui

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.view.View
import android.view.ViewTreeObserver
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.home.adapter.HomeBannerAdapter
import com.zhkj.txg.module.home.adapter.HomeCateAdapter
import com.zhkj.txg.module.home.adapter.MarketGoodsAdapter
import com.zhkj.txg.module.home.entity.BannerEntity
import com.zhkj.txg.module.home.vm.TopViewModel
import com.zhkj.txg.utils.GridItemDecoration
import com.zhkj.txg.utils.typeJump
import com.youth.banner.Banner
import kotlinx.android.synthetic.main.activity_top_product.*
import kotlin.math.abs

class TopProductActivity : ViewModelActivity<TopViewModel>() {

    companion object {
        fun open(activity: Activity) {
            val intent = Intent(activity, TopProductActivity::class.java)
            activity.startActivity(intent)
        }
    }

    override fun statusTitleBar(): View? = topViewTop
    override fun setViewModel(): TopViewModel = createViewModel()
    override val layoutResId: Int = R.layout.activity_top_product

    private lateinit var bannerTop: Banner<BannerEntity, HomeBannerAdapter>
    private var maxScrollHeight = 0
    private val categoryAdapter = HomeCateAdapter().apply {
        setOnItemClickListener { _, _, position ->
            val entity = data[position]
            ProductListActivity.topOpen(this@TopProductActivity, entity.name, entity.id)
        }
    }
    private val productAdapter = MarketGoodsAdapter().apply {
        loadMoreModule?.isEnableLoadMore = true
        loadMoreModule?.setOnLoadMoreListener { viewModel.topProduct(AccountManager.getToken()) }
    }

    override fun initViewModel() {
        viewModel.topProductLiveData.observe(this, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // 数据填充
                    if (it.loadMore) productAdapter.addData(it.data)
                    else productAdapter.setNewData(it.data)
                    // 判断加载状态
                    if (it.hasMore) productAdapter.loadMoreModule?.loadMoreComplete()
                    else productAdapter.loadMoreModule?.loadMoreEnd()
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    productAdapter.loadMoreModule?.loadMoreFail()
                }
            }
        })
        viewModel.topLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) it.response?.data?.let { data ->
                // 设置轮播图
                bannerTop.setDatas(data.banner).start()
                // 设置分类
                categoryAdapter.setNewData(data.category)
            }
        })
    }

    override fun initUI() {
        // 获取变色的最大滚动距离
        topViewTop.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                maxScrollHeight =
                    (ScreenUtil.getScreenWidth(this@TopProductActivity) * 0.75 - topViewTop.measuredHeight).toInt()
                topViewTop.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
        with(rvTopProduct) {
            layoutManager = GridLayoutManager(context, 3)
            adapter = productAdapter
            addItemDecoration(
                GridItemDecoration(ScreenUtil.dip(context, 20), ScreenUtil.dip(context, 10))
            )
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                val llm = layoutManager as LinearLayoutManager
                val pos = IntArray(2)
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    // 设置title的透明度
                    if (llm.findFirstVisibleItemPosition() == 0 && llm.getChildAt(0) != null) {
                        llm.getChildAt(0)!!.getLocationInWindow(pos)
                        if (abs(pos[1]) <= maxScrollHeight) {
                            val alpha = (abs(pos[1]).toFloat() / maxScrollHeight * 255).toInt()
                            topViewTop.setBackgroundColor(Color.argb(alpha, 255, 255, 255))
                            titleTopProduct.setLeftIcon(R.drawable.ic_back)
                            tvTopSearch.setBackgroundResource(R.drawable.bg_round_white_30dp_transparent)
                        } else {
                            titleTopProduct.setLeftIcon(R.drawable.ic_arrow_left_black)
                            topViewTop.setBackgroundColor(Color.argb(255, 255, 255, 255))
                            tvTopSearch.setBackgroundResource(R.drawable.bg_round_gray_100)
                        }
                    }
                }
            })
        }
        with(productAdapter) {
            setEmptyView(R.layout.layout_empty_data)
            headerWithEmptyEnable = true
            setHeaderView(createHeaderView())
        }
        // 打开搜索页面
        tvTopSearch.setOnClickListener {
            SearchActivity.topOpen(this)
        }
        // 打开购物车
        ivBasket.setOnClickListener {
            startActivity(Intent(this, CartActivity::class.java))
        }
    }

    override fun initData() {
        viewModel.topData(AccountManager.getToken())
    }

    /**
     * 生成顶部视图
     */
    private fun createHeaderView(): View {
        return layoutInflater.inflate(R.layout.item_top_header, null).apply {
            bannerTop = findViewById(R.id.bannerTop)
            bannerTop.addBannerLifecycleObserver(this@TopProductActivity).setAdapter(HomeBannerAdapter(context))
                .setOnBannerListener { data, _ ->
                    (data as? BannerEntity)?.let {
                        typeJump(this@TopProductActivity, it.jumpType ?: 0, it.params, it.title)
                    }
                }
            with(findViewById<RecyclerView>(R.id.rvTop)) {
                layoutManager = GridLayoutManager(this@TopProductActivity, 5)
                adapter = categoryAdapter
            }
        }
    }
}